package com.itheima.homework.bh2005;
/*
【编号2005】有一个存放牛奶的箱子，送奶工将牛奶放入箱子，而用户从箱子中获取到牛奶，
假设箱子只能存储一瓶牛奶，请编写程序模拟牛奶的存储和获取过程。
 */
public class Test5 {
    public static void main(String[] args) {
    //送奶工
        new Thread(()->{
            int count=0;
            while (true){
                synchronized ("箱子"){
                    if (Box.count==0){
                        break;
                    }else {
                        if (Box.flag){
                            try {
                                "箱子".wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }else {
                            count++;
                            System.out.println("送第"+count+"瓶奶");
                            Box.flag=true;
                            "箱子".notify();
                        }
                    }
                }
            }
        }).start();


        //消费者
        new Thread(()->{
            int count=0;
            while (true){
                synchronized ("箱子"){
                    if (Box.count==0){
                        break;
                    }else {
                        if (Box.flag){
                            count++;
                            System.out.println("取走第"+count+"瓶奶");
                            Box.count--;
                            Box.flag=false;
                            "箱子".notify();
                        }else {
                            try {
                                "箱子".wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }).start();
    }
}
class Box{
    public static boolean flag=false;
    public static int count=5;
}